#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "socklib.h"
#include <string.h>
#include <sys/time.h>

#define LEN 256
#define HOST "192.168.100.199"
#define PORT 4000

void talk_with_server(int fd);
long gettime();

int main(int argc, char *argv[])
{
    int port = PORT;
    char *host;

    if (argc == 1) {
        host = HOST;
    }
    else {
        host = argv[1];
        if (argc > 2) {
            port = atoi(argv[2]);
       }
    }
    printf("connect_to_server: host: %s, port: %d\n", host, port);
    int sock_id = connect_to_server(host, port);
    if (sock_id == -1){
        return -1;
    }

    talk_with_server(sock_id);

    close(sock_id);

    return 0;
}

void talk_with_server(int fd)
{
    char buf[LEN];
    int n;
    
    memset(buf,0, LEN);
    printf("Talking with server...\n");
    while (1) {
        char *s = fgets(buf, LEN, stdin);
        if (s == NULL) {
            perror("fgets");
            return;
        }
        if (strlen(buf) == 1) {
            strncpy(buf,"POOLING_PARK", strlen("POOLING_PARK"));
        }
        else {
            buf[strlen(buf) - 1] = '\0';
            if (strcmp(buf, "exit") == 0) {
                printf("exit talking...\n");
                return;
            }
        }
        long startime = gettime();  
        n = sendMsg(fd, buf);
        if (n < 0) {
             return;
        }
        n = recvMsg(fd, buf, LEN);
        if (n < 0) {
             return;
        }
        long endtime = gettime();
        printf("recv msg: %s, len: %d, usetime: %ldus \n", 
                buf,(int)strlen(buf), endtime - startime);
   }
}

// return us
long gettime()
{
    struct timeval v;
    gettimeofday(&v, (struct timezone *) NULL);
    return (v.tv_sec * 1000000 + v.tv_usec);
}


